define(function(require) {

    require('../../../c/base/index');

    require('../../../c/nav/index');

    var firstTime = true;
    var hongbaoInfo = [];

    var userHongbao = {
        init: function() {
            //初始化菜单选中效果
            $(".fa-circle-o").each(function() {
                if ($(this).parents("a").text() == "用户红包查询") {
                    $(this).parents("a").parents("li").addClass("active");
                }
            });
            this.initTable();
            this.initValidator();
            this.bindEvent();
        },
        /**
         * 执行查询操作.
         */
        doSearch: function() {
            if ($("#mobile").val() || $("#userid").val()) {
                $("#J_Search").data('bootstrapValidator').validate();
                if ($("#J_Search").data('bootstrapValidator').isValid()) {
                    if ($('#hongbao_type').find("option:selected").val() > 0) {
                        $('#hongbao_table').DataTable().ajax.reload();
                    } else {
                        alert("请选择红包类型!");
                    }
                }
            } else {
                alert("请输入用户手机或用户ID！");
            }
        },
        /**
         * 初始化店铺的列表
         */
        initTable: function() {
            var self = this;
            $("#hongbao_table").dataTable({
                "oLanguage": CRM.pageConfig,
                "sScrollX": "100%", //表格的宽度
                "sScrollXInner": "100%", //表格的内容宽度
                "bScrollCollapse": true, //当显示的数据不足以支撑表格的默认的高度时，依然显示纵向的滚动条。(默认是false)
                "bPaginate": true, //是否显示分页
                "bLengthChange": true, //每页显示的记录数
                "bFilter": false, //搜索栏
                "bSort": false, //是否支持排序功能
                "bInfo": true, //显示表格信息
                "bAutoWidth": false, //自适应宽度
                "bServerSide": true, //开启服务端处理
                "sAjaxSource": CRM.getOuterUrl('/crm/crm/market/queryHongbaoByUserId'),
                "fnInitComplete": function() {
                    this.fnAdjustColumnSizing(true);
                },
                "fnServerData": function(sSource, aoData, fnCallback) {
                    if (firstTime) {
                        firstTime = false;
                        return;
                    }
                    var _url = "";
                    if ($('#hongbao_type').find("option:selected").val() == 1) {
                        _url = CRM.getOuterUrl('/crm/crm/market/queryHongbaoByUserId');
                    } else if ($('#hongbao_type').find("option:selected").val() == 2) {
                        _url = CRM.getOuterUrl('/crm/crm/market/queryCardCouponByUserId');
                    } else if ($('#hongbao_type').find("option:selected").val() == 3) {
                        //_url = CRM.getOuterUrl('/crm/crm/market/queryGoodsCouponByUserId');
                        //_url = 'http://daily.market.51xianqu.com/market/api/coupon/queryGoodsCouponByUserId.jsonp';
                        _url = checkURL("/market/api/coupon/queryGoodsCouponByUserId.jsonp");
                    }
                    var dataString = "";
                    var requestType = "";
                    if ($('#hongbao_type').find("option:selected").val() == 3){
                        dataString = {
                            "mobile": $("#mobile").val(),
                            "userId": $("#userid").val(),
                            "userStatus": $("#userStatus").val(),
                            "currentPage": aoData[3].value / aoData[4].value + 1,
                            "pageSize": aoData[4].value
                        };
                        requestType = "GET";
                    } else {
                        dataString = JSON.stringify({
                            "mobile": $("#mobile").val(),
                            "userId": $("#userid").val(),
                            "userStatus": $("#userStatus").val(),
                            "page": aoData[3].value / aoData[4].value + 1,
                            "pageSize": aoData[4].value
                        });
                        requestType = "POST";
                    }
                    if (!($("#mobile").val() || $("#userid").val())) {
                        return;
                    }
                    CRM.request({
                        "type": requestType,
                        "url": _url,
                        "dataType": "json",
                        contentType: "application/json",
                        xhrFields: {
                            withCredentials: true
                        },
                        "data": dataString,
                        contentType: "application/json",
                        "success": function(req) {
                            if (req.status) {
                                var resultData = CRM.getDataTabelDtaObject();
                                if (req.entry) {
                                    hongbaoInfo = req.entry.list;
                                    //hongbaoInfo下添加红包类型判断参数
                                    //hongbaoInfo.hongbaoType = $('#hongbao_type').find("option:selected").val();
                                    resultData.iTotalDisplayRecords = req.entry.allRow;
                                    resultData.iTotalRecords = req.entry.allRow;
                                    if ($('#hongbao_type').find("option:selected").val() == 1) {
                                        for (var length in req.entry.list) {
                                            resultData.aaData.push([
                                                req.entry.list[length].couponName,
                                                req.entry.list[length].price,
                                                req.entry.list[length].startTime,
                                                req.entry.list[length].expirationTime,
                                                req.entry.list[length].status,
                                                length
                                            ])
                                        }
                                    } else if ($('#hongbao_type').find("option:selected").val() == 2) {
                                        for (var length in req.entry.list) {
                                            resultData.aaData.push([
                                                req.entry.list[length].name,
                                                "\\",
                                                req.entry.list[length].startTime,
                                                req.entry.list[length].expirationTime,
                                                req.entry.list[length].status,
                                                length
                                            ])
                                        }
                                    } else if ($('#hongbao_type').find("option:selected").val() == 3) { //卡券返回项渲染
                                        for (var length in req.entry.list) {
                                            resultData.aaData.push([
                                                req.entry.list[length].name,
                                                "\\",
                                                req.entry.list[length].startTime,
                                                req.entry.list[length].expirationTime,
                                                req.entry.list[length].status,
                                                length
                                            ])
                                        }
                                    }
                                } else {
                                    CRM.showDialog(req.message);
                                }
                                fnCallback(resultData);
                            } else {
                                CRM.showDialog(req.message);
                            }
                        }
                    });
                },
                "aaSorting": [
                    [1, "asc"]
                ], //给列表排序 ，第一个参数表示数组 (由0开始)。1 表示Browser列。第二个参数为 desc或是asc
                "aoColumns": [{
                        "sTitle": "红包名称",
                        "bSortable": true
                    }, {
                        "sTitle": "红包价格(元)",
                        "bSortable": true,
                        "mRender": function(data, type, row) {
                            if (data == "\\") {
                                return data;
                            } else {
                                return data / 100;
                            }
                        }
                    }, {
                        "sTitle": "开始时间",
                        "bSortable": true
                    }, {
                        "sTitle": "过期时间",
                        "bSortable": true
                    }, {
                        "sTitle": "红包状态",
                        "bSortable": true,
                        "mRender": function(data, type, row) {
                            var _returnStr = "";
                            if (data === 0) {
                                _returnStr = "未使用";
                            } else {
                                _returnStr = "使用";
                            }
                            return _returnStr;
                        }
                    }, {
                        "sTitle": "操作",
                        "bSortable": true,
                        "mRender": function(data, type, row) {
                            var html = "";
                            if ($('#hongbao_type').find("option:selected").val() == 1){
                                html += '<div class="btn btn-default" onclick="showDetail(' + data + ')">查看详情</div><div class="btn btn-default" onclick="hongbaoCancel(' + data + ')">取消红包</div>';
                            }else {
                                html += '<div class="btn btn-default" onclick="showDetail(' + data + ')">查看详情</div>';
                            }
                            return html;
                        }
                    }

                ], //列设置，表有几列，数组就有几项
                "bStateSave": true, //保存状态到cookie *************** 很重要 ， 当搜索的时候页面一刷新会导致搜索的消失。使用这个属性就可避免了
                "sPaginationType": "full_numbers" //分页，一共两种样式，full_numbers和two_button(默认)

            });
        },
        /*取消红包*/
        hongbaoCancel: function (index) {
            console.log(hongbaoInfo[index]);
            var hongbaoCancelId = hongbaoInfo[index].id;
            CRM.request({
                url: checkURL("/market/api/coupon/updateShopCouponStatusNotAvaliable.jsonp"),
                    //'http://daily.market.51xianqu.com/market/api/coupon/updateShopCouponStatusNotAvaliable.jsonp',
                type: 'GET',
                dataType: 'json',
                async: false,
                data: {
                    "id": hongbaoCancelId
                },
                success:function (req) {
                    if (req.status){
                        $('#hongbao_table').DataTable().ajax.reload();
                        CRM.showDialog("取消成功");
                    } else {
                        if (req.message){
                            CRM.showDialog(req.message);
                        } else {
                            CRM.showDialog("请登录后再进行操作");
                        }
                    }
                }
            });
        },

        /*
         URL判断对应返回接口
         */
        checkURL: function (api) {
            var currentHost = window.location.host;
            if ((currentHost.indexOf("daily") > -1)||(currentHost.indexOf("dev") > -1)){
                return "http://daily.market.51xianqu.com" + api;
            } else if (currentHost.indexOf("gray") > -1){
                return "http://gray.market.51xianqu.com" + api;
            } else {
                return "http://market.51xianqu.com" + api;
            }
        },

        /*
         * 红包详情
         */
        showDetail: function(index) {
            console.log(hongbaoInfo[index]);
            if ($('#hongbao_type').find("option:selected").val() == 3){
                var baseItem = hongbaoInfo[index].baseItem;
                if (baseItem){
                    if(typeof(baseItem.itemName) == "undefined" || baseItem.itemName.length==0){
                        itemName = "无";
                    }else{
                        itemName = baseItem.itemName;
                    }
                    if(typeof(baseItem.cardUsers) == "undefined" || baseItem.cardUsers.length==0){
                        cardUsers = "无";
                    }else{
                        cardUsers = baseItem.cardUsers.join(',');
                    }
                    if(typeof(baseItem.TOKENLimit) == "undefined" || baseItem.TOKENLimit.length==0){
                        TOKENLimit = "无";
                    }else{
                        TOKENLimit = baseItem.TOKENLimit.join(',');
                    }
                    cardUserLimit = typeof(baseItem.cardUserLimit) != "undefined" ? baseItem.cardUserLimit : "无";
                    if(typeof(baseItem.cardGetCode) == "undefined" || baseItem.cardGetCode.length==0){
                        cardGetCode = "无";
                    }else{
                        cardGetCode = baseItem.cardGetCode.join(',');
                    }
                    if(typeof(baseItem.cardAPP) == "undefined" || baseItem.cardAPP.length==0){
                        cardAPP = "无";
                    }else{
                        cardAPP = baseItem.cardAPP.join(',');
                    }
                } else {
                    itemName = '无';
                    cardUsers = "无";
                    TOKENLimit = "无";
                    cardUserLimit = "无";
                    cardGetCode = "无";
                    cardAPP = "无";
                }
                $('#itemName').val(itemName);
                $('#cardUsers').val(cardUsers);
                $('#TOKENLimit').val(TOKENLimit);
                $('#cardUserLimit').val(cardUserLimit);
                $('#cardGetCode').val(cardGetCode);
                $('#cardAPP').val(cardAPP);
                $('#kaquanPropertyModal').modal("show");
            } else {
                var hongbaoProperty = hongbaoInfo[index].hongbaoProperty;
                if (hongbaoProperty) {
                    if(typeof(hongbaoProperty.useCity) == "undefined" || hongbaoProperty.useCity.length==0){
                        useCity = "无";
                    }else{
                        useCity = hongbaoProperty.useCity.join(',');
                    }
                    if(typeof(hongbaoProperty.useShopName) == "undefined" || hongbaoProperty.useShopName.length==0){
                        useShopName = "无";
                    }else{
                        useShopName = hongbaoProperty.useShopName.join(',');
                    }
                    if(typeof(hongbaoProperty.excludeCatName) == "undefined" || hongbaoProperty.excludeCatName.length==0){
                        excludeCatName = "无";
                    }else{
                        excludeCatName = hongbaoProperty.excludeCatName.join(',');
                    }
                    minOrderPrice = typeof(hongbaoProperty.minOrderPrice) != "undefined" ? hongbaoProperty.minOrderPrice : "无";
                    if (hongbaoProperty.sourcePage == "NOLIMIT") {
                        sourcePage = "普通";
                    } else if (hongbaoProperty.sourcePage == "GROUP") {
                        sourcePage = "拼团";
                    } else if (hongbaoProperty.sourcePage == "PRESELL") {
                        sourcePage = "预售";
                    } else {
                        sourcePage = "无";
                    }
                    if(typeof(hongbaoProperty.useType)=="undefined"){
                        useType = "无";
                    }else if(hongbaoProperty.useType=="to_b"){
                        useType = "商城";
                    }else{
                        useType = "普通";
                    }
                } else {
                    useCity = "无";
                    useShopName = "无";
                    excludeCatName = "无";
                    minOrderPrice = "无";
                    useType = "无";
                    sourcePage = "无"
                }
                $('#useCity').val(useCity);
                $('#useShopName').val(useShopName);
                $('#excludeCatName').val(excludeCatName);
                $('#minOrderPrice').val(minOrderPrice);
                $('#useType').val(useType);
                $('#sourcePage').val(sourcePage);
                $('#hongbaoPropertyModal').modal("show");
            }
        },
        /**
         * 表单验证初始化
         */
        initValidator: function() {
            $('#J_Search').bootstrapValidator({
                message: '输入错误',
                feedbackIcons: {
                    valid: 'glyphicon glyphicon-ok',
                    invalid: 'glyphicon glyphicon-remove',
                    validating: 'glyphicon glyphicon-refresh'
                },
                fields: {
                    mobile: {
                        message: 'error',
                        validators: {
                            phone: {
                                country: 'CN',
                                message: '请输入正确的电话格式'
                            }
                        }
                    },
                    userid: {
                        message: 'error',
                        validators: {
                            regexp: {
                                regexp: /^[0-9]+$/,
                                message: '请输入数字'
                            }
                        }
                    }
                }
            });
        },
        bindEvent: function() {
            var self = this;
            $("#search_btn").on('click', function() {
                self.doSearch();
            });
        }
    };

    window.doSearch = $.proxy(userHongbao.doSearch, userHongbao);
    window.showDetail = $.proxy(userHongbao.showDetail, userHongbao);
    window.hongbaoCancel = $.proxy(userHongbao.hongbaoCancel, userHongbao);
    window.checkURL = $.proxy(userHongbao.checkURL, userHongbao);

    userHongbao.init();
});
